package edu.whu.puppygo.security;

import edu.whu.puppygo.dao.UserDao;
import edu.whu.puppygo.exception.BackendException;
import edu.whu.puppygo.util.GlobalUser;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 创建一个UserDetailsService的Bean，从数据库中读取用户和权限信息
 */
@Service
public class DbUserDetailService implements UserDetailsService {

    @Resource
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        edu.whu.puppygo.entity.User user = userDao.findByUsernameAndDeleteTimeNull(username).orElseThrow(() -> new BackendException("该用户不存在"));
        GlobalUser.setUser(user);
        return User.builder()
                .username(username)
                .password(user.getPassword())
                .authorities("USER")
                .build();
    }


}
